let axios = require('axios')
let db = require('./db/sqlite.js')
let fs = require('fs')
let task = require('./task')

class History {
  constructor() {
    this.tableName = 'ssc_history'
    this.db = new db.SqliteDB(`./db/${this.tableName}`);
  }

  create() {
    let sql = `CREATE TABLE ${this.tableName}(
      ID INTEGER PRIMARY KEY AUTOINCREMENT,
      opendate          TEXT    NOT NULL,
      officialopendate  TEXT    NOT NULL,
      issueno           TEXT    NOT NULL,
      issue_number      TEXT    INTEGER,
      number            TEXT    NOT NULL,
      a                 INTEGER,
      b                 INTEGER,
      c                 INTEGER,
      d                 INTEGER,
      e                 INTEGER,
      refernumber       TEXT,
      saleamount        TEXT,
      totalmoney        TEXT,
      prize             TEXT
    )`
    console.log(sql)
    this.db.createTable(sql)
  }

  async insert(data) {
    return new Promise(async (resolve, reject) => {
      try {
        console.log('>>>insert', JSON.stringify(data))
        data.issue_number = parseInt(data.issueno.replace('-', ''))
        let numberArr = data.number.split(/\s/)
        data.a = parseInt(numberArr[0])
        data.b = parseInt(numberArr[1])
        data.c = parseInt(numberArr[2])
        data.d = parseInt(numberArr[3])
        data.e = parseInt(numberArr[4])

        let arr = [
          data.opendate, data.officialopendate, data.issueno, data.issue_number, data.number, data.a, data.b, data.c, data.d, data.e
        ]

        let sql = ` INSERT INTO ${this.tableName} (opendate,officialopendate,issueno,issue_number,number,a,b,c,d,e)
                  VALUES ( ?,?,?,?,?,?,?,?,?,?);`
        console.log(sql)
        console.log(arr)
        let result = await this.query({
          issue_number: data.issue_number
        })
        if (!result.length) {
          this.db.insertData(sql, [arr], res => {
            resolve()
          })
        } else {
          console.log('重复,未插入。')
          resolve()
        }
      } catch (err) {
        console.error(err)
        reject(err)
      }
    })
  }

  query(data = {}) {
    console.log('>>>query', JSON.stringify(data))
    return new Promise((resolve, reject) => {
      try {
        let sql = ` select * from ${this.tableName} where 1=1 `
        if (data.select) {
          sql = sql.replace('*', data.select)
        }

        if (data.issue_number) {
          sql += `and issue_number=${data.issue_number}`
        }
        if (data.where) {
          sql += ` ${data.where}`
        }
        if (data.order) {
          sql += ` ${data.order}`
        }
        console.log(sql)
        this.db.queryData(sql, res => {
          resolve(res)
        })
      } catch (err) {
        console.log(err)
        reject(err)
      }
    })
  }
  queryData(sql) {
    return new Promise((resolve, reject) => {
      try {
        this.db.queryData(sql, res => {
          resolve(res)
        })
      } catch (err) {
        console.log(err)
        reject(err)
      }
    })
  }
  executeSql(sql) {
    return new Promise((resolve, reject) => {
      try {
        this.db.executeSql(sql, res => {
          resolve(res)
        })
      } catch (err) {
        console.log(err)
        reject(err)
      }
    })
  }
  async getData(start = 0, issueno = '', num = 1) {
    console.log('>>>start', start)
    return new Promise(async (resolve, reject) => {
      let url = `http://api.jisuapi.com/caipiao/history?appkey=76a323709e6a0a85&caipiaoid=73&issueno=${issueno}&start=${start}&num=${num}`
      console.log('url', url)
      axios.get(url).then(async res => {
        if (parseInt(res.data.status) === 0) {
          let list = res.data.result.list
          list.forEach(async item => {
            await this.insert(item)
          })
        } else {
          console.error(res.data.msg)
        }
        resolve()
      }).catch(err => {
        console.error(err)
        reject()
      })
    })
  }
  async test() {
    let list = await this.query({
      order: 'order by issue_number'
    })
    let tailList = []
    list.forEach(item => {
      tailList.push(item.a)
      // tailList.push(item.b)
      // tailList.push(item.c)
      // tailList.push(item.d)
      // tailList.push(item.e)
    })
    console.log(tailList.length)
    fs.writeFileSync('./dist/tail.json', JSON.stringify(tailList))
    //算法1  设定最大遗漏，进行买入
    // task.algorithm1(85, 8); //遗漏期数，最大倍投数
    // task.algorithm2(); //猜大小
    // console.log(list.length)
    // fs.writeFileSync('./dist/sscno.json', JSON.stringify(list))
  }
  thread(index = 0, len = 10) {
    function start() {
      index += 19;
      (function (index, start) {
        index++
        setTimeout(_ => {
          console.log('>>>', index)
          let url = `http://api.jisuapi.com/caipiao/history?appkey=76a323709e6a0a85&caipiaoid=73&issueno=&start=${index}&num=20`
          console.log(url)
          axios.get(url).then(async res => {
            if (parseInt(res.data.status) === 0) {
              let list = res.data.result.list
              fs.writeFileSync(`./dist/temp/${index}.json`, JSON.stringify(list))
              start()
            } else {
              console.log(res.data.msg)
              start()
            }

          }).catch(err => {
            console.error(err)
            setTimeout(_ => {
              start()
            })
          })
        }, 100)
      })(index, start)
    }
    for (let i = 0; i < len; i++) {
      start();
    }
  }

  /**
   * 读取./dist/temp/*.json内容到数据库
   */
  async addData() {
    let list = []
    fs.readdirSync('./dist/temp').forEach(filename => {
      list = list.concat(JSON.parse(fs.readFileSync(`./dist/temp/${filename}`)))
    })
    for (let i = 0; i < list.length; i++) {
      await this.insert(list[i])
    }

  }

  async main() {
    // history.create()
    console.log('>>>app start')
    // await history.getData(69000)
    // await history.test();
    // history.thread(123000, 10)
    // await this.addData()
    // let list = await history.query()
    // console.log(list.length)
    console.log('>>>app end')
    // history.query({
    //   // issue_number:20190203077
    // })
  }
}

let history = new History()
// history.main()


module.exports = history
